package com.siteseat.common.misc;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;

import org.apache.commons.lang3.StringUtils;

/**
 *
 */
public class TimeHelper {

  private static ThreadLocal<SimpleDateFormat> FORMATTER = new ThreadLocal<SimpleDateFormat>();

  //

  public static SimpleDateFormat formatter() {
    SimpleDateFormat r = FORMATTER.get();
    if( r == null ) {
      r = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss", Locale.US );
      FORMATTER.set( r );
    }
    return r;
  }

  /**
   * @param value
   * @return
   */
  public static String format( java.util.Date value ) {
    return formatter().format( value );
  }
  
  public static String formatCurrentTime() {
    return format( System.currentTimeMillis() );
  }

  /**
   * @param value
   * @return
   */
  public static String format( long milliseconds ) {
    return format( new java.util.Date( milliseconds ) );
  }

  /**
   * @param text
   * @return
   * @throws ParseException
   */
  public static java.sql.Timestamp parse( String text ) throws ParseException {
    if( StringUtils.isBlank( text ) ) {
      return null;
    }
    return new java.sql.Timestamp( formatter().parse( text ).getTime() );
  }

  /**
   * @return Timestamp
   */
  public static Timestamp now() {
    return new Timestamp( System.currentTimeMillis() );
  }

  /**
   * @param last
   * @param interval
   * @return
   */
  public static boolean passedSince( long last, long interval ) {
    long now = System.currentTimeMillis();
    return ( now > last + interval );
  }

}
